<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" class="m-r-8" :model="queryParams" :inline="true">
        <el-form-item class="input-box">
          <div class="input-group">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入用户昵称"
              clearable
              @keyup.enter="handleQuery"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="currentPageData" highlight-current-row row-key="userID">
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center" width="120">
          <template #default="scope">
            <img class="avatar" :src="scope.row.avatar" alt="用户头像" />
          </template>
        </el-table-column>
        <el-table-column label="昵称" align="center">
          <template #default="scope">
            {{ scope.row.nickname }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="default"
              icon="Location"
              @click.stop="getLoginLog(scope.row.userID)"
            >
              查看登录日志
            </el-button>
            <el-button
              type="primary"
              link
              size="default"
              icon="Document"
              @click.stop="getLearningRecord(scope.row.userID)"
            >
              查看学习记录
            </el-button>
            <el-button
              type="primary"
              link
              size="default"
              icon="EditPen"
              @click.stop="getStudyPlan(scope.row.userID)"
            >
              查看学习计划
            </el-button>
            <el-button
              :type="scope.row.state === 1 ? 'danger' : 'success'"
              link
              size="default"
              :icon="scope.row.state === 1 ? 'TurnOff' : 'Open'"
              @click.stop="handleStatusChange(scope.row)"
            >
              {{ scope.row.state === 1 ? "禁用" : "启用" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination p-8">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog v-model="logVisible" title="登录日志" width="500" @close="loginLogList = []">
      <div v-if="loginLogList.length > 0">
        <el-table :data="loginLogList" stripe>
          <el-table-column label="序号" width="80">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="loginTime" label="登录时间" />
        </el-table>
      </div>
      <div v-else class="text-center py-10 text-gray-500">暂无登录日志</div>
    </el-dialog>

    <el-dialog
      v-model="learnRecordVisible"
      title="学习记录"
      width="1000"
      @close="learnRecordList = []"
    >
      <div v-if="learnRecordList.length > 0">
        <el-table :data="learnRecordList" stripe>
          <el-table-column label="序号" width="80">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="课程名称" width="200">
            <template #default="scope">
              {{ scope.row.yitle || scope.row.title }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="课程类型" width="120" />
          <el-table-column prop="createdTime" label="开始时间" width="180" />
          <el-table-column prop="lastWatchTime" label="最后学习时间" width="180" />
          <el-table-column label="学习进度" width="200">
            <template #default="scope">
              <el-progress
                :percentage="Number(scope.row.progress) || 0"
                :format="(percentage) => `${percentage}%`"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="text-center py-10 text-gray-500">暂无学习记录</div>
    </el-dialog>
    <el-dialog v-model="studyPlanVisible" title="学习计划" width="1000" @close="studyPlanList = []">
      <div v-if="studyPlanList.length > 0">
        <el-table :data="studyPlanList" stripe>
          <el-table-column label="序号" width="80">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="content" label="计划内容" />
          <el-table-column prop="creationTime" label="创建时间" width="180" />
          <el-table-column prop="planStart" label="计划开始时间" width="180" />
          <el-table-column prop="planDate" label="计划日期" width="180" />
        </el-table>
      </div>
      <div v-else class="text-center py-10 text-gray-500">暂无学习计划</div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "@/http/index"; // 引入封装的http模块

// 定义用户信息类型
interface WxUserItem {
  userID: string;
  openID?: string;
  nickname?: string;
  avatar?: string;
  state: number; // 0=禁用，1=启用
  lastLoginTime?: string;
  learningCount?: number;
}

// 定义登录日志类型
interface LoginLogItem {
  id?: string;
  userID?: string;
  loginTime?: string;
  logOutTime?: string;
  weChatUserName?: string;
  loginState?: string;
}

// 定义学习计划类型
interface StudyPlanItem {
  id?: string;
  userID?: string;
  creationTime?: string;
  planStart?: string;
  planDate?: string;
  content?: string;
}

// 定义学习记录类型（注意：包含可能的拼写错误字段yitle）
interface LearningRecordItem {
  id?: string;
  userID?: string;
  lessonId?: string;
  progress?: number;
  lastWatchTime?: string;
  createdTime?: string;
  updatedTime?: string;
  type?: string;
  cover?: string;
  title?: string;
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 查询参数
const queryParams = reactive({
  keyword: "",
});

// 数据列表
const wxUserList = ref<WxUserItem[]>([]);
const currentPageData = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return wxUserList.value.slice(startIndex, endIndex);
});

// 加载状态
const loading = ref(false);

// 初始化加载数据
onMounted(async () => {
  await handleQuery();
});

// 处理查询
async function handleQuery() {
  loading.value = true;
  try {
    const result = await http.getWxUserList(queryParams.keyword);
    // 修复：正确处理用户列表数据（移除错误的result.data = result）
    wxUserList.value = Array.isArray(result) ? result : result?.data || [];
    pagination.total = wxUserList.value.length;
    pagination.currentPage = 1;
    if (queryParams.keyword) {
      ElMessage.info(`搜索到 ${pagination.total} 条结果`);
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败，请重试");
  } finally {
    loading.value = false;
  }
}

// 分页处理
function handleSizeChange(size: number) {
  pagination.pageSize = size;
}

function handleCurrentChange(page: number) {
  pagination.currentPage = page;
}
let loginLogList = <LoginLogItem[]>[];
const logVisible = ref(false);
let learnRecordList = <LearningRecordItem[]>[];
const learnRecordVisible = ref(false);
let studyPlanList = <StudyPlanItem[]>[];
const studyPlanVisible = ref(false);
async function getLoginLog(userId?: string) {
  if (!userId) return;
  try {
    const response = await http.getWxUserLoginLog(userId);
    response.data = response;
    loginLogList = response.data;
    logVisible.value = true;
  } catch (error) {
    console.error("获取登录日志失败:", error);
    ElMessage.error("获取登录日志失败");
    loginLogList = [];
  }
}

// 获取学习记录
async function getLearningRecord(userId?: string) {
  if (!userId) return;
  try {
    const response = await http.getWxUserLearningRecord(userId);
    response.data = response;
    learnRecordList = response.data;
    learnRecordVisible.value = true;
  } catch (error) {
    console.error("获取学习记录失败:", error);
    ElMessage.error("获取学习记录失败");
    learnRecordList = [];
  }
}

// 获取学习计划
async function getStudyPlan(userId?: string) {
  if (!userId) return;
  try {
    const response = await http.getWxUserStudyPlan(userId);
    response.data = response;
    studyPlanList = response.data;
    studyPlanVisible.value = true;
  } catch (error) {
    console.error("获取登录日志失败:", error);
    ElMessage.error("获取登录日志失败");
    studyPlanList = [];
  }
}

// 处理状态变更
async function handleStatusChange(row: WxUserItem) {
  if (!row.userID) return;

  const action = row.state === 1 ? "禁用" : "启用";
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户【${row.nickname || "未知用户"}】吗？`,
      "操作确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: action === "禁用" ? "warning" : "info",
      }
    );

    loading.value = true;
    await http.changeWxUserState(row.userID);

    // 更新本地状态
    row.state = row.state === 1 ? 0 : 1;
    // 强制刷新列表
    wxUserList.value = [...wxUserList.value];
    ElMessage.success(`${action}成功`);
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${action}用户失败:`, error);
      ElMessage.error(`${action}用户失败，请重试`);
    }
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.input-group {
  display: flex;
  gap: 10px;
}

.avatar {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 50%;
}

.pagination {
  float: right;
}

.text-center {
  text-align: center;
}

.py-10 {
  padding-top: 2.5rem;
  padding-bottom: 2.5rem;
}

.text-gray-500 {
  color: #94a3b8;
}
</style>
